package com.rfid;

import android.content.Context;

import com.hoho.android.usbserial.util.SerialInputOutputManager;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author Administrator
 * @date 2020/11/28
 */
public class RFIDUsbDevice {
    public Map<String, byte[]> mCommandMap = new HashMap<>();
    private UsbReader mUsbReader;
    private RFIDDataAnalysis mRFIDDataAnalysis;
    private Timer mTimer;


    public RFIDUsbDevice(Context context) {
        mCommandMap.put("queryOnce", new byte[]{(byte) 0xBB, 0x00, 0x22, 0x00, 0x00, 0x22, 0x7E});
//        mCommandMap.put("queryOnce", new byte[]{(byte) 0xBB, 0x00, 0x39, 0x00, 0x09,
//                0x00, 0x00,0x00, 0x00, 0x00,
//                0x03,
//                0x00, 0x00, 0x00, 0x02,
//                0x35, 0x7E});
        mRFIDDataAnalysis = new RFIDDataAnalysis(null);
        mUsbReader = new UsbReader(context, 4292, 60000, new SerialInputOutputManager.Listener() {
            @Override
            public void onNewData(byte[] data) {
                mRFIDDataAnalysis.analysis(data);
//                String str = bytesToHexString(data);
//                Log.e("newData", str == null ? "" : str);
            }

            @Override
            public void onRunError(Exception e) {
                //  ToastUtils.showShort("电子标签读写器连接失败");
            }
        });
    }

    public static String bytesToHexString(byte[] src) {

        StringBuilder stringBuilder = new StringBuilder();

        if (src == null || src.length <= 0) {

            return null;

        }

        for (int i = 0; i < src.length; i++) {

            int v = src[i] & 0xFF;

            String hv = Integer.toHexString(v);

            if (hv.length() < 2) {

                stringBuilder.append(0);

            }

            stringBuilder.append(hv);

        }

        return stringBuilder.toString();

    }

    public void start() {
        if (mUsbReader != null) {
            mUsbReader.start();
        }
    }

    public void stop() {
        if (mUsbReader != null) {
            mUsbReader.stop();
        }
        if (mRFIDDataAnalysis != null) {
            mRFIDDataAnalysis.stop();
        }
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    public void queryOnce() {
        byte[] data = mCommandMap.get("queryOnce");
        if (data != null) {
            if (mTimer != null) {
                mTimer.cancel();
                mTimer = null;
            }
            mTimer = new Timer();
            mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    mUsbReader.send(data);
                }
            }, 0, 20);
        }
    }
} 